"""
告警事件管理相关的数据模型
"""
from datetime import datetime
from decimal import Decimal
from typing import Optional, List, Annotated

from pydantic import BaseModel, ConfigDict, BeforeValidator

from common.base_enums import AlarmStatus, AlarmCloseReason


# 定义空字符串转None的验证函数
def empty_str_to_none(v):
	if isinstance(v, str) and v.strip() == "":
		return None
	return v


class AlarmBase(BaseModel):
	"""告警基础模型"""
	meter_code: str
	alarm_type: str
	status: AlarmStatus = AlarmStatus.OPEN
	close_reason: Annotated[Optional[AlarmCloseReason], BeforeValidator(empty_str_to_none)] = None
	work_order_id: Optional[int] = None
	raised_at: datetime = None


class AlarmCreate(AlarmBase):
	"""创建告警请求模型"""
	pass


class AlarmUpdate(BaseModel):
	"""更新告警请求模型"""
	status: Optional[AlarmStatus] = None
	close_reason: Annotated[Optional[AlarmCloseReason], BeforeValidator(empty_str_to_none)] = None
	work_order_id: Optional[int] = None


class Alarm(AlarmBase):
	"""告警完整模型"""
	id: int
	updated_at: datetime

	model_config = ConfigDict(from_attributes=True)


class AlarmRuleBase(BaseModel):
	"""告警规则基础模型"""
	rule_code: str
	severity: int = 2  # 1提示 2一般 3严重
	enabled: bool = True


class AlarmRuleCreate(AlarmRuleBase):
	"""创建告警规则请求模型"""
	pass


class AlarmRuleUpdate(BaseModel):
	"""更新告警规则请求模型"""
	severity: Optional[int] = None
	enabled: Optional[bool] = None


class AlarmRule(AlarmRuleBase):
	"""告警规则完整模型"""
	id: int
	rule_name: str
	rule_code: str
	severity: Optional[int] = None
	threshold: Optional[Decimal] = None
	unit: Optional[str] = None
	operator: Optional[str] = None

	model_config = ConfigDict(from_attributes=True)


class AlarmWorkBase(BaseModel):
	"""告警工单关联基础模型"""
	alarm_id: int
	work_order_id: int


class AlarmWorkCreate(AlarmWorkBase):
	"""创建告警工单关联请求模型"""
	pass


class AlarmWork(AlarmWorkBase):
	"""告警工单关联完整模型"""
	id: int
	created_at: datetime

	model_config = ConfigDict(from_attributes=True)


class AlarmTimelineItem(BaseModel):
	"""告警时间线项"""
	time: datetime
	action: str
	comment: Optional[str] = None


class AlarmDetail(Alarm):
	"""告警详情模型"""
	current_voltage: Optional[float] = None
	current_current: Optional[float] = None
	timeline: List[AlarmTimelineItem] = []


class AlarmRuleResponse(AlarmRule):
	"""告警规则响应模型（带标签）"""
	severity_label: str

	model_config = ConfigDict(from_attributes=True)
